package com.cetc;

import org.junit.Test;

import java.io.*;

/**
 * @Classname IORandomAccessFileTest
 * @Description RandomAccessFile 随机存取文件流的使用
 * @Date 2022/11/25 11:38
 * @Created by louzhuangxi
 */
public class IORandomAccessFileTest {
    /**
     * 在文件中插入字符
     */
    @Test
    public void test01() {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile("data/hello1.txt", "rw");
            raf.seek(2);
            byte[] cBuf = new byte[5];
            int len;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = raf.read(cBuf)) != -1) {
                bos.write(cBuf, 0, len);
            }
            raf.seek(2);
            raf.write("xyz".getBytes());
            raf.write(bos.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
